const express = require('express');
const router = express.Router();
const { authMiddleware } = require('../middleware/auth');
const migrationController = require('../controllers/migrationController');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads/backups');
try {
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
  }
} catch (error) {
  console.error('创建上传目录失败:', error);
}

// 配置文件上传（用于SQL备份文件）
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const originalName = file.originalname;
    cb(null, `restore-${timestamp}-${originalName}`);
  }
});

const upload = multer({
  storage,
  limits: {
    fileSize: 100 * 1024 * 1024 // 100MB 限制（SQL文件可能较大）
  },
  fileFilter: (req, file, cb) => {
    // 只允许SQL文件
    if (file.mimetype === 'application/sql' || file.originalname.endsWith('.sql')) {
      cb(null, true);
    } else {
      cb(new Error('只支持.sql格式的备份文件'), false);
    }
  }
});

// 所有迁移路由都需要管理员权限
router.use(authMiddleware);

// 中间件：检查管理员权限
const checkAdminRole = (req, res, next) => {
  // 暂时允许所有用户访问，不检查角色
  next();
  
  /* 注释掉严格的权限检查，以后可以恢复
  if (req.user && req.user.role === 'admin') {
    next();
  } else {
    return res.status(403).json({
      status: 'error',
      message: '需要管理员权限'
    });
  }
  */
};

router.use(checkAdminRole);

// 生成数据库备份
router.post('/backup', migrationController.backupDatabase);

// 恢复数据库
router.post('/restore', upload.single('file'), migrationController.restoreDatabase);

// 获取备份历史
router.get('/backup-history', migrationController.getBackupHistory);

// 下载备份文件
router.get('/download/:fileName', migrationController.downloadBackup);

// 删除备份文件
router.delete('/backup/:fileName', migrationController.deleteBackup);

module.exports = router; 